package com.dependencies.springjdbc.controller;

import com.dependencies.springjdbc.model.User;
import com.dependencies.springjdbc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhizhou   2024/7/29 23:22
 */

@RestController
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping
    public List<User> findAll() {
        return userService.findAll();
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<User> findById(@PathVariable int id) {
        User user = userService.findById(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @PostMapping
    public ResponseEntity<String> save(@RequestBody User user) {
        int result = userService.save(user);
        if (result == 1) {
            return ResponseEntity.ok("用户信息创建成功");
        } else {
            return ResponseEntity.status(500).body("用户信息更新失败");
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<String> update(@PathVariable int id, @RequestBody User user) {
        user.setId(id);
        int result = userService.update(user);
        if (result == 1) {
            return ResponseEntity.ok("用户信息更新成功");
        } else {
            return ResponseEntity.status(500).body("用户信息更新失败");
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteById(@PathVariable int id) {
        int result = userService.deleteById(id);
        if (result == 1) {
            return ResponseEntity.ok("用户信息删除成功");
        } else {
            return ResponseEntity.status(500).body("用户信息删除失败");
        }
    }
}
